
#include "KeyNode.h"

KeyNode::KeyNode() {

}

KeyNode::~KeyNode() {
	for(KeyNode::iterator iter = this->begin(); iter != this->end(); ++iter)
		if (*iter) delete *iter;
}

Clave* KeyNode::findClave(Clave* clave){

	if (this->empty()) return NULL;

	//Busco la clave mayor o igual a la que me pasan por parametro
	KeyNode::const_iterator iter = this->lower_bound(clave);

	if (iter == this->end()) return *(--iter);

	if (*(*iter) == *clave)	return *iter;

	if (iter == this->begin()) return NULL;

	return *(--iter);

}

Clave* KeyNode::findClaveAnterior(Clave* clave){

	if (this->empty()) return NULL;

	//Busco la clave mayor o igual a la que me pasan por parametro
	KeyNode::const_iterator iter = this->lower_bound(clave);

	if (iter == this->begin()) return NULL;

	return *(--iter);

}

Clave* KeyNode::findClaveSiguiente(Clave* clave){

	if (this->empty()) return NULL;

	//Busco la clave mayor o igual a la que me pasan por parametro
	KeyNode::const_iterator iter = this->upper_bound(clave);

	if (iter == this->end()) return NULL;

	return *iter;

}

KeyNode* KeyNode::splitBSharp(unsigned short minClaves, unsigned short maxClaves, bool hoja) {

	KeyNode* conjClavesMayores = new KeyNode();
	KeyNode::iterator iter = this->begin();

	unsigned short i;

	for(i = 0; (iter != this->end()) && (i < minClaves); ++iter)
		i += (*iter)->getTamanioEnDisco();

	if (i > maxClaves) --iter;

	for (KeyNode::iterator iterMayores = iter;
		iterMayores != this->end(); ++iterMayores)
		conjClavesMayores->insert(*iterMayores);

	this->erase(iter, this->end());

	//Se impide que queden nodos vacíos.
	if ( (!hoja) && (conjClavesMayores->size() == 0) && (this->size() > 2) ){
		iter = this->end();
		conjClavesMayores->insert(*(--iter));
		this->erase(iter);
		conjClavesMayores->insert(*(--iter));
		this->erase(iter);
	}
	else if ( (conjClavesMayores->size() == 1) && (this->size() > 1) ){
		iter = this->end();
		conjClavesMayores->insert(*(--iter));
		this->erase(iter);
	}


	return conjClavesMayores;
}

void KeyNode::merge(KeyNode* keyNode, Clave* c1, Clave* c2) {

	if (c1) this->insert(c1);
	if (c2) this->insert(c2);

	for (KeyNode::iterator iter = keyNode->begin(); iter != keyNode->end(); ++iter)
		this->insert(*iter);

	keyNode->clear();

}

void KeyNode::merge(KeyNode* keyNode1, KeyNode* keyNode2, Clave* c1, Clave* c2) {

	this->merge(keyNode1, c1, c2);

	for (KeyNode::iterator iter = keyNode2->begin(); iter != keyNode2->end(); ++iter)
		this->insert(*iter);

	keyNode2->clear();

}


KeyNode& KeyNode::operator = (KeyNode& keyNode) {

	this->clear();

	for (KeyNode::const_iterator iter = keyNode.begin(); iter != keyNode.end(); ++iter)
		this->insert((*iter)->copiar());

	return *this;

}
